<template>
  <view class="protocol-detail-container">
    <!-- 协议标题 -->
    <view class="protocol-header">
      <text class="protocol-title">{{ protocolData.title || '协议详情' }}</text>
    </view>

    <!-- 协议内容 -->
    <view class="protocol-content">
      <view class="content-section">
        <text class="content-title">协议内容</text>
        <view class="content-text">
          <editor id="editor" class="content-editor" :read-only="true" :show-img-toolbar="false"
            :show-img-resize="false" :placeholder="'暂无内容'" @ready="onEditorReady" />
        </view>
      </view>

      <view class="content-section" v-if="protocolData.terms && protocolData.terms.length > 0">
        <text class="content-title">协议条款</text>
        <view class="content-text">
          <text class="paragraph" v-for="(term, index) in protocolData.terms" :key="index">
            {{ index + 1 }}. {{ term }}
          </text>
        </view>
      </view>

    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 错误状态 -->
    <view v-if="error" class="error-container">
      <view class="error-icon">⚠️</view>
      <text class="error-text">{{ error }}</text>
      <button class="retry-btn" @click="loadProtocolDetail">重试</button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getAgreement } from '@/api/user.js'

// 协议数据
const protocolData = ref({})
const loading = ref(false)
const error = ref('')

// 编辑器上下文与待设置内容
const editorCtx = ref(null)
const pendingHtml = ref('')

// 获取路由参数中的协议ID
const getProtocolId = () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const options = currentPage.options
  return options.id
}

// 将内容写入编辑器（安全调用）
const setEditorContent = (html) => {
  if (editorCtx.value && typeof editorCtx.value.setContents === 'function') {
    editorCtx.value.setContents({ html })
  } else {
    pendingHtml.value = html || ''
  }
}

// 加载协议详情
const loadProtocolDetail = async () => {
  const id = getProtocolId()
  if (!id) {
    error.value = '协议ID不存在'
    return
  }

  try {
    loading.value = true
    error.value = ''

    const res = await getAgreement(id)
    if (res.code === 200) {
      protocolData.value = res.data || {}
      // 接口返回后再设置到editor
      setEditorContent(protocolData.value.content || '')
    } else {
      error.value = res.msg || '获取协议详情失败'
    }
  } catch (err) {
    console.error('获取协议详情失败:', err)
    error.value = '网络异常，请重试'
  } finally {
    loading.value = false
  }
}

const onEditorReady = () => {
  // 获取editor组件实例
  uni.createSelectorQuery()
    .select('#editor')
    .context((res) => {
      editorCtx.value = res && res.context ? res.context : null
      // 如果有待写入内容，立即回填
      if (pendingHtml.value) {
        setEditorContent(pendingHtml.value)
        pendingHtml.value = ''
      } else if (protocolData.value && protocolData.value.content) {
        setEditorContent(protocolData.value.content)
      }
    })
    .exec()
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 页面加载时获取协议信息
onMounted(() => {
  loadProtocolDetail()
})
</script>

<style>
.protocol-detail-container {
  height: calc(100vh - 100rpx);
  background-color: #fff;
  overflow-y: auto;
}

.page-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  font-weight: bold;
  color: #000;
  margin-right: 60rpx;
}

.protocol-header {
  padding: 30rpx;
  text-align: center;
  background-color: #f0f0f0;
  border-bottom: 1rpx solid #eee;
}

.protocol-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.protocol-content {
  padding: 30rpx;
}

.content-section {
  margin-bottom: 40rpx;
}

.content-section:last-child {
  margin-bottom: 0;
}

.content-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.content-text {
  background-color: #fafafa;
  border-radius: 8rpx;
  padding: 20rpx;
}

.content-editor {
  height: 100%;
  background-color: transparent;
}

.content-editor :deep(.ql-editor) {
  padding: 0;
  background-color: transparent;
  border: none;
  font-size: 28rpx;
  line-height: 1.6;
  color: #333;
}


.paragraph {
  font-size: 28rpx;
  line-height: 1.6;
  color: #666;
  margin-bottom: 16rpx;
  display: block;
}

.paragraph:last-child {
  margin-bottom: 0;
}

.loading-container {
  padding: 30rpx;
  text-align: center;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}

.error-container {
  padding: 30rpx;
  text-align: center;
  background-color: #fffbe6;
  border: 1rpx solid #ffe58f;
  border-radius: 12rpx;
  margin: 30rpx;
}

.error-icon {
  font-size: 60rpx;
  color: #faad14;
  margin-bottom: 10rpx;
}

.error-text {
  font-size: 28rpx;
  color: #faad14;
  margin-bottom: 20rpx;
}

.retry-btn {
  background-color: #1890ff;
  color: #fff;
  padding: 10rpx 20rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
}
</style>
